package com.GPS_based_training.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * This class is needed for creating and upgrading the database.
 * @author Pietro Meloni
 */
public class DatabaseHelper extends SQLiteOpenHelper {

	//Constant used for operating with the db
	public static final String DATABASE_NAME = "trainings.db";
    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_NAME = "training";
    public static final String KEY_ID = "_id";
    public static final String KEY_JSON_COLUMN = "json_training";
    public static final String KEY_NAME_COLUMN = "training_name";
    
    //Database QUERY needed for creating the database. 
    private static final String DATABASE_CREATE = "create table "+ TABLE_NAME +
    		" ( " + KEY_ID + " integer primary key autoincrement, " +
    		KEY_JSON_COLUMN + " text not null); ";
    
	/**
	 * @author Pietro Meloni
	 * 
	 * Constructor based on a context
	 * @see android.database.sqlite.SQLiteOpenHelper
	 */
    public DatabaseHelper(Context context) {
    	
    	super(context, DATABASE_NAME, null, DATABASE_VERSION);
    	
	}
    
    @Override
    /**
     * @author Pietro Meloni
     * 
     * Is called by the framework, if the database is accessed but not yet created
     * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
     */
    public void onCreate(SQLiteDatabase database) {
    	
    	database.execSQL(DATABASE_CREATE);
    }

    @Override
    /**
     * @author Pietro Meloni
     * 
     * Called if the database version is increased. This method allows to update
     * the database schema or to drop it and recreate it via the onCreate() method.
     * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
     */
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
    	
    	Log.w(DatabaseHelper.class.getName(),"Upgrading database from version " + oldVersion + " to " +
    	      newVersion + ", which will destroy all old data");
    	
    	database.execSQL("DROP TABLE IF EXISTS training");
    	
    	onCreate(database);
	}
   
    
}
